package com.bea.ftd.dashboard.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bea.ftd.common.ValidationException;
import com.bea.ftd.common.dao.PartnerInfoRepo;
import com.bea.ftd.common.entity.PartnerInfo;
import com.bea.ftd.common.enums.ValidationErrorCode;
import com.bea.ftd.dashboard.service.IGatewayService;
import com.bea.ftd.dashboard.service.IPartnerInfoService;
import com.bea.ftd.dashboard.validator.BooleanValidator;
import com.bea.ftd.dashboard.validator.CustomTypeValidator;
import com.bea.ftd.dashboard.validator.NumberValidator;
import com.bea.ftd.dashboard.validator.StringValidator;

@Service
public class PartnerInfoServiceImpl implements IPartnerInfoService, IGatewayService {
	private Logger LOGGER = LoggerFactory.getLogger(PartnerInfoServiceImpl.class);

	@Autowired
	private PartnerInfoRepo partnerInfoRepo;
	
	@Autowired
	private StringValidator stringValidator;
	@Autowired
	private BooleanValidator booleanValidator;
	@Autowired
	private NumberValidator numberValidator;
	@Autowired
	private CustomTypeValidator customTypeValidator;

	@Override
	public void addPartnerInfo(PartnerInfo partnerInfo) throws ValidationException {
		validateInputParams(partnerInfo);
		setCreateOrUpdateTime(partnerInfo, partnerInfoRepo);
		partnerInfoRepo.save(partnerInfo);
	}
	
	
	/**
	 * 验证输入参数是否有效
	 * 
	 * @param partnerInfo
	 * @throws ValidationException
	 */
	private void validateInputParams(PartnerInfo partnerInfo) throws ValidationException {
		
		if (stringValidator.isEmptyString(partnerInfo.getPartnerCode())) {
			throw new ValidationException(ValidationErrorCode.EMPTY_VALUE, "合作商号不能为空");
		}
		
		if (stringValidator.isEmptyString(partnerInfo.getPartnerName())) {
			throw new ValidationException(ValidationErrorCode.EMPTY_VALUE, "合作商名称不能为空");
		}
		
		if (!numberValidator.isNonNegtiveNumber(partnerInfo.getSecretId())) {
			throw new ValidationException(ValidationErrorCode.INVALID_NUMBER, "私钥ID不能为空");
		}
		
		if (!booleanValidator.isBooleanType(partnerInfo.getIsActivate())) {
			throw new ValidationException(ValidationErrorCode.INVALID_BOOLEAN_VALUE, "无效的isActivate值");
		}
		
		if (!customTypeValidator.isValidMessageType(partnerInfo.getMsgInType())) {
			throw new ValidationException(ValidationErrorCode.INVALID_BOOLEAN_VALUE, "无效的输入报文类型");
		}
		
		if (!customTypeValidator.isValidMessageType(partnerInfo.getMsgOutType())) {
			throw new ValidationException(ValidationErrorCode.INVALID_BOOLEAN_VALUE, "无效的输出报文类型");
		}
		
	}

	@Override
	public List<PartnerInfo> getAllPartnerInfos() {
		try {
			return partnerInfoRepo.findAll();
		} catch (Exception e) {
			LOGGER.error("error when querying partnerInfo from database " + e.getMessage());
			return null;
		}
	}
}
